package com.lh_travel.lohas.activity;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.lh_travel.lohas.R;
import com.lh_travel.lohas.base.api;
import com.lh_travel.lohas.base.baseActivity;
import com.lh_travel.lohas.domain.Version;
import com.tamic.novate.Throwable;
import com.tamic.novate.callback.RxResultCallback;
import java.io.File;
import java.text.DecimalFormat;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

public class SplashActivity extends baseActivity {

    private String verName;
    private LinearLayout ll_pro;
    private ProgressBar pb_update;
    private TextView tv_pro;
    private DownloadManager manager;
    private long dwnid;
    private TimerTask task;

    @SuppressLint("HandlerLeak")
    private Handler downHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what){
                case 0:
                    ll_pro.setVisibility(View.GONE);

                    String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath() + File.separator + filename;

                    installApk(path);
                    break;

                case 1:

                    String pro = msg.getData().getString("pro");

                    float v = Float.parseFloat(pro) * 100;

                    tv_pro.setText(v + "%");
                    pb_update.setProgress((int) v);

                    break;
            }

        }
    };
    private String downloaddir;
    private String filename;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_splash);

        findView();
        bindListner();
        ensureUI();
    }

    @Override
    public void findView() {
        ll_pro = (LinearLayout) findViewById(R.id.ll_pro);
        pb_update = (ProgressBar) findViewById(R.id.pb_update);
        tv_pro = (TextView) findViewById(R.id.tv_pro);
    }

    @Override
    public void bindListner() {

    }

    @Override
    public void ensureUI() {

        //检查是否app更新
        verName = getVerName();

        new api(mContext).getVesion(versionCallBack);
    }

    public String getVerName() {
        String verName = "";
        try {
            verName = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    private RxResultCallback versionCallBack = new RxResultCallback<Version>() {
        @Override
        public void onNext(Object tag, int code, String message, final Version response) {

            if (code == 200) {

                if (verName.equals(response.version)) {

                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {

                            Intent intent = new Intent(mContext, HomeActivity.class);

                            startActivity(intent);

                            finish();

                        }
                    }, 1000);

                } else {

                    //检测到有新的app要下载;

                    showMyDialog2("更新提示", "检测到有新版本更新", "更新", response.force == 0 ? "取消" : "关闭", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            ll_pro.setVisibility(View.VISIBLE);

                            downloadApk(response.url);
                            dialog2.dismiss();
                        }

                    }, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                            if (response.force == 0) {

                                Intent intent = new Intent(mContext, HomeActivity.class);

                                startActivity(intent);
                                dialog2.dismiss();
                                finish();

                            } else {

                                System.exit(0);

                            }
                        }
                    });

                }
            }
        }

        @Override
        public void onError(Object tag, Throwable e) {

        }

        @Override
        public void onCancel(Object tag, Throwable e) {

        }
    };

    /**
     * 你最好加一个文件系统的权限
     * @param url
     */
    private void downloadApk(String url) {

        try {
            Random ran = new Random(System.currentTimeMillis());

            filename = "lohas.upgrade." + ran.nextInt(100000) + ".apk";

            DownloadManager.Request request = new DownloadManager.Request(
                    Uri.parse(url));
            String appname = this.getResources().getString(R.string.app_name);
            request.setDescription(appname);
            request.setTitle("开始下载新版本");
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

            downloaddir = Environment.DIRECTORY_DOWNLOADS;

            if (downloaddir.contains("://")) {
                downloaddir = "download";
            }

            Environment.getExternalStoragePublicDirectory(downloaddir).mkdir();

            request.setDestinationInExternalPublicDir(downloaddir, filename);

            manager = (DownloadManager) this
                    .getSystemService(Context.DOWNLOAD_SERVICE);


            dwnid = manager.enqueue(request);

            //-------------------------------//

            final DownloadManager.Query query = new DownloadManager.Query();
            Timer timer = new Timer();

            task = new TimerTask() {
                @Override
                public void run() {
                    Cursor cursor = manager.query(query.setFilterById(dwnid));
                    if (cursor != null && cursor.moveToFirst()) {
                        if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {

                            downHandler.sendEmptyMessage(0);

                            task.cancel();
                        }

                        int downsize = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                        int totalsize = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                        // float pro = downsize  / totalsize;

                        DecimalFormat df = new DecimalFormat("0.00");
                        String pro = df.format((float) downsize / totalsize);

                        if (totalsize != -1) {

                            Message msg = Message.obtain();
                            msg.what = 1;

                            Bundle bundle = new Bundle();
                            bundle.putString("pro", pro);

                            msg.setData(bundle);

                            downHandler.sendMessage(msg);
                        }
                    }
                    cursor.close();
                }
            };
            timer.schedule(task, 0, 200);

            //-------------------------------//

            String message = "开始下载新版本";
            showMessage(message);

        } catch (Exception e) {
            e.printStackTrace();
            showMessage("下载文件出错,请到各应用市场下载,搜索 乐活旅行");
        }
    }

    private void installApk(String path) {

        try {

            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(Uri.parse("file://" + path), "application/vnd.android.package-archive");
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(i);

        } catch (Exception e) {
            Log.e("splashActivity", "安装失败");
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (downHandler != null){
            downHandler = null;
        }
    }
}
